<?php

namespace App\Http\Controllers\Strator;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Model;
use App\Models\Strator\StratorPurchase;
use App\Models\Strator\StratorProduct;
use App\Models\Strator\StratorPurchaseDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Strator\StratorSupplier;
use App\Models\Strator\StratorCustomer;

class StratorPurchaseController extends Controller
{
    protected Request $request;
    protected Model $model;

    public function __construct(Request $request,StratorPurchase $strator)
    {
        $this->request=$request;
        $this->model = $strator;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $perPage=$this->request->per_page??10;
        if($this->request->filled('start')&&$this->request->filled('end')){
            $list=$this->model
            ->modelSearch($this->request,$this->model)
            ->whereBetween('time',[$this->request->start,$this->request->end])
            // ->with(['detail'])
            ->orderBy('status', 'asc')
            ->orderBy('id', 'desc')
            ->paginate($perPage);
        } else {
            $list=$this->model
            ->modelSearch($this->request,$this->model)
            // ->with(['detail'])
            ->orderBy('status', 'asc')
            ->orderBy('id', 'desc')
            ->paginate($perPage);
        }
        $this->saveOperationLog('查询采购单列表');
        return $this->success($list);
    }
    public function getItem()
    {
        if($this->request->filled('supplier_name')){
            $list=StratorPurchaseDetail::query()
            ->where('supplier_name', $this->request->supplier_name)
            ->where('type', 1);
            if($this->request->filled('start')&&$this->request->filled('end')){
                $list=$list->whereBetween('in_time',[$this->request->start,$this->request->end]);
            }
            if($this->request->filled('productId')){
                $list=$list->where('product_id', $this->request->productId)
                ->orderByDesc('id');
            }elseif($this->request->filled('product_id')){
                $list=$list->where('product_id', $this->request->product_id)
                ->orderByDesc('id');
            }elseif($this->request->filled('productName')){
                $list=$list->where('product_name', $this->request->productName)
                ->orderByDesc('id');
            }else{
                $list=$list->orderByDesc('id');
            }
        }elseif($this->request->filled('customer_name')){
            $list=StratorPurchaseDetail::query()
            ->where('customer_name', $this->request->customer_name)
            ->where('type', 2);
            if($this->request->filled('start')&&$this->request->filled('end')){
                $list=$list->whereBetween('out_time',[$this->request->start,$this->request->end]);
            }
            if($this->request->filled('productId')){
                $list=$list->where('product_id', $this->request->productId)
                ->orderByDesc('id');
            }elseif($this->request->filled('product_id')){
                $list=$list->where('product_id', $this->request->product_id)
                ->orderByDesc('id');
            }elseif($this->request->filled('productName')){
                $list=$list->where('product_name', $this->request->productName)
                ->orderByDesc('id');
            }else{
                $list=$list->orderByDesc('id');
            }
        }else{
            $list=StratorPurchaseDetail::query()
            ->where('product_id', $this->request->product_id)
            ->where('type', $this->request->type);
            if($this->request->filled('start')&&$this->request->filled('end')){
                if($this->request->type==1){
                    $list=$list->whereBetween('in_time',[$this->request->start,$this->request->end]);
                }else{
                    $list=$list->whereBetween('out_time',[$this->request->start,$this->request->end]);
                }
            }
            if($this->request->filled('productId')){
                $list=$list->where('product_id', $this->request->productId)
                ->orderByDesc('id');
            }elseif($this->request->filled('productName')){
                $list=$list->where('product_name', $this->request->productName)
                ->orderByDesc('id');
            }else{
                $list=$list->orderByDesc('id');
            }
        }
        $this->saveOperationLog('查询采购单详情');
        if($this->request->filled('page')&&!$this->request->filled('productId')&&!$this->request->filled('productName')){
            $perPage=$this->request->per_page??10;
            return $this->success($list->paginate($perPage));
        }else{
            return $this->success($list->get());
        }
    }

    /**
     * Show the form for creating a new resource.干什么？
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store()
    {
        $data=$this->request->only($this->storeOnly());
        $data['order_sn'] = $this->getSn();
        // 2是转为生产单，3是转为入库单
        if ($this->request->status==2) {
            // $this->buildDetail($this->request,$data['order_sn']);
        }
        if ($this->request->status==3) {
            // $this->buildDetail($this->request,$data['order_sn']);
        }
        // 如果供应商或者客户是数据库里没有的，那么就新增
        if($this->request->filled('supplier_name')){
            $supplier = StratorSupplier::query()->where('name', $this->request->supplier_name)->count();
            if(empty($supplier)||$supplier==0) {
                $adddata = [];
                $adddata[0] = [
                    'created_at'=>now(),
                    'name'=>$this->request->supplier_name,
                ];
                DB::table('strator_suppliers')->insert($adddata);
            }
        }
        $this->model->fill($data);
        $this->model->save();
        $this->saveOperationLog('新增采购单');
        return $this->success(['id'=>$this->model->id]);
    }
    // 暂时弃用
    protected function buildDetail($request,$order_sn){
        // 按数据生成出入库明细
        $contents = json_decode($request->contents);
        $data = [];
        for ($i=0;$i<count($contents);$i++){
            if ($request->type==1) {
                $this->updateProductQuantityAdd($contents[$i]->productId, $contents[$i]->quantity);
            } else {
                $this->updateProductQuantityDel($contents[$i]->productId, $contents[$i]->quantity);
            }
            $data[$i]= [
                'order_sn'=> $order_sn,
                'created_at'=>now(),
                'batch_no'=>$request->batch_no??'',
                'remark'=>$request->remark??'',
                'in_time'=>$request->in_time??null,
                'out_time'=>$request->out_time??null,
                'type'=>$request->type??1,
                'in_type'=>$request->in_type??1,
                'out_type'=>$request->out_type??1,
                'out_type'=>$request->out_type??1,
                'status'=>2,
                'supplier_name'=>$request->supplier_name??'',
                'customer_name'=>$request->customer_name??'',
                'operator'=>$request->operator??'',
                'operator_id'=>$request->operator_id??null,
                'product_name'=>$contents[$i]->productName,
                'product_id'=>$contents[$i]->productId,
                'quantity'=>$contents[$i]->quantity,
                'product_type'=>$contents[$i]->product_type??'',
                'product_attr'=>$contents[$i]->product_attr??'',
            ];
        }

        if(count($data)>0){
            DB::table('strator_purchase_details')->insert($data);
        }
    }
    // 产品库存增加
    protected function updateProductQuantityAdd($product_id,$quantity){
        // 找到对应产品
        $product = StratorProduct::query()->where('id',$product_id)->first();
        $product->is_instore = 1; // 更新为已操作过入库
        $product->inventory = $product->inventory+$quantity;
        $product->save();
    }
    // 产品库存减少
    protected function updateProductQuantityDel($product_id,$quantity){
        // 找到对应产品
        $product = StratorProduct::query()->where('id',$product_id)->first();
        $product->is_instore = 1; // 更新为已操作过入库
        $product->inventory = $product->inventory-$quantity;
        $product->save();
    }
    //设置订单号
    private function getSn(){
        $car = StratorPurchase::query()
            ->select('id')
            ->where('id','>',0)
            ->orderByDesc('id')
            ->first();
        if($car){
            $num = $car->id+1;
        }else{
            $num = 1;
        }
        if ($num<10) {
            $num = '000'.$num;
        } elseif ($num<100) {
            $num = '00'.$num;
        } elseif ($num<1000) {
            $num = '0'.$num;
        }
        return 'cgd'.date('Ymd',time()).$num;
    }
    //
    public function storeOnly():array{
        return [
            'sort',
            'remark',
            'status',
            'time',
            'type',
            'order_sn',
            'supplier_name',
            'share_contents',
            'contents',
            'operator',
            'operator_id',
            'batch_no',
        ];
    }

    /**
     * Display the specified resource.
     */
    public function show()
    {
//        return $this->success($this->request->user());
        $model=$this->model->findOrFail($this->request->id);
        return $this->success($model);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update()
    {
        $model=$this->model->findOrFail($this->request->id);
        if ($this->request->filled('contents') && $this->request->status==2) {
            // $this->buildDetail($this->request,$model->order_sn);
        }
        $origin=$model->toArray();
        $data=$this->request->except($this->updateExcept());
        $model->fill($data);
        $model->save();
        $this->saveOperationLog('修改采购单',$origin);
        return $this->successMsg();
    }
    //
    public function updateExcept():array
    {
        return [
            'id',
        ];
    }
    /**
     * Remove the specified resource from storage.
     */
    public function destroy()
    {
        $model=$this->model->findOrFail($this->request->id);
        $model->delete();
        $this->saveOperationLog('删除采购单草稿');
        return $this->successMsg('删除成功');
    }
}
